﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.IO;
using System.Web;

namespace XCommunity.Documents.UBB
{
  public class UbbRender
  {

    private HtmlTextWriter _writer;


    public UbbRender( HtmlTextWriter writer )
    {
      _writer = writer;
    }

    public void RenderDocument( UbbDocument document )
    {
      RenderChildren( document );
    }


    private void RenderChildren( IUbbContainer block )
    {
      foreach ( object item in block.Childrens )
      {
        RednerItem( item );
      }
    }

    private void RednerItem( object item )
    {
      string text = item as string;

      if ( text != null )
      {
        RenderText( text );
        return;
      }


      UbbBlock block = item as UbbBlock;

      if ( block != null )
      {
        RednerBlock( block );
        return;
      }


      UbbElement element = item as UbbElement;

      if ( element != null )
      {
        RenderElement( element );
        return;
      }


    }

    private void RednerBlock( UbbBlock block )
    {

      switch ( block.TagName )
      {
        case "style":
          _writer.AddAttribute( HtmlTextWriterAttribute.Style, block.Parameter.Replace( "\"", "" ) );
          _writer.RenderBeginTag( HtmlTextWriterTag.Span );

          RenderChildren( block );

          _writer.RenderEndTag();
          break;

        case "p":
          _writer.AddAttribute( HtmlTextWriterAttribute.Style, block.Parameter.Replace( "\"", "" ) );
          _writer.RenderBeginTag( HtmlTextWriterTag.P );

          RenderChildren( block );

          _writer.RenderEndTag();
          break;

        case "b":
          _writer.RenderBeginTag( HtmlTextWriterTag.B );

          RenderChildren( block );

          _writer.RenderEndTag();
          break;

        case "link":
          _writer.AddAttribute( HtmlTextWriterAttribute.Href, block.Parameter.Replace( "\"", "" ) );
          _writer.RenderBeginTag( HtmlTextWriterTag.A );

          RenderChildren( block );

          _writer.RenderEndTag();
          break;


      }

    }

    private void RenderElement( UbbElement element )
    {
      switch ( element.TagName )
      {
        case "img":
          _writer.AddAttribute( HtmlTextWriterAttribute.Src, element.InnerText );
          _writer.RenderBeginTag( HtmlTextWriterTag.Img );
          break;
        default:
          throw new Exception();
      }
    }

    private void RenderText( string text )
    {
      using ( StringReader reader = new StringReader( text ) )
      {
        _writer.Write( HttpUtility.HtmlEncode( text ).Replace( "\n", "<br />" ) );
      }
    }
  }
}
